import React, { useEffect, useRef, useState } from 'react'
import style from './selection.module.css'
import { useAppSelector, useAppDispatch } from '../../app/hooks'
import { toggleType, type, leftSelect, rightSelect, rightAttentionList, leftAttentionList, clearLeftSelect, clearRightSelect, clearRightAttentionList, clearLeftAttentionList, savaIndexAttentionAsync, savaIndexSelectAsync, setLoadMoreToTrue, loadMore } from '../../features/home/homeSlice'

import { CurType } from '../../myTypes'
import SelectList from '../publicComponents/SelectList'
import AttentionList from '../Mine/AttentionList'
import { InfiniteScroll, Toast } from 'antd-mobile'
import Loading from '../publicComponents/Loading'
import { useNavigate } from 'react-router-dom'

export default function NavSelection() {
  const dispatch = useAppDispatch()
  const leftSelectData = useAppSelector(leftSelect)
  const rightSelectData = useAppSelector(rightSelect)
  const leftAttentionListData = useAppSelector(rightAttentionList)
  const rightAttentionListData = useAppSelector(leftAttentionList)
  const curType = useAppSelector(type)
  const navigate = useNavigate()
  let [page, setPage] = useState(1)
  let [userId, setUserId] = useState('')
  const hasMore = useAppSelector(loadMore)

  // 判断是否登录
  useEffect(() => {
    const id = localStorage.getItem('userId')
    if (id) {
      userId = id
      setUserId(id)
    } else {
      navigate('/login')
    }
  }, [])

  function toggleNav(type: CurType) {
    if (type === curType) return
    dispatch(toggleType(type))
    dispatch(setLoadMoreToTrue(true))
    page = 1
    setPage(1)
    dispatch(clearLeftSelect([]))
    dispatch(clearRightSelect([]))
    dispatch(clearLeftAttentionList([]))
    dispatch(clearRightAttentionList([]))
    if (window.pageYOffset > 715) {
      window.scrollTo(0, 715)
    }
  }

  function load() {
    return new Promise<string>(async (resolve) => {
      if (curType !== '我的关注') {
        await dispatch(
          savaIndexSelectAsync({
            pageNum: page,
            pageSize: 10,
            accountId: userId
          })
        )
        resolve('')
      } else {
        await dispatch(
          savaIndexAttentionAsync({
            pageNum: page,
            pageSize: 10,
            accountId: userId,
            userId: userId
          })
        )
        resolve('')
      }
    })
  }

  async function loadMoreData() {
    Toast.show({
      content: '加载中...',
      maskClickable: false,
      duration: 0,
      icon: <Loading />
    })
    await load()
    Toast.clear()
    setPage((prePage) => {
      return prePage + 1
    })
  }

  return (
    <div className={style.container}>
      <div className={style['nav-list']}>
        <span className={`${style['nav-item']} ${curType === '猜你喜欢' ? style.active : ''}`} onClick={() => toggleNav('猜你喜欢')}>
          猜你喜欢
        </span>
        <span className={`${style['nav-item']} ${curType === '热门去处' ? style.active : ''}`} onClick={() => toggleNav('热门去处')}>
          热门去处
        </span>
        <span className={`${style['nav-item']} ${curType === '我的关注' ? style.active : ''}`} onClick={() => toggleNav('我的关注')}>
          我的关注
        </span>
      </div>

      {/* 猜你喜欢和热门去处显示 */}
      {curType !== '我的关注' && (
        <div>
          <SelectList leftSelect={leftSelectData} rightSelect={rightSelectData} />
        </div>
      )}

      {/* 我的关注展示 */}
      {curType === '我的关注' && (
        <div className={style['select-collection']}>
          {/* 没有数据时展示 */}
          {leftAttentionList.length === 0 && rightAttentionList.length === 0 && <div className={style.empty}>暂无相关的圈子</div>}
          {/* 关注数据展示 */}
          <AttentionList style={style} leftSelect={leftAttentionListData} rightSelect={rightAttentionListData} />
        </div>
      )}
      <InfiniteScroll loadMore={loadMoreData} hasMore={hasMore} threshold={0}>
        {!hasMore && <span>--- 我是有底线的 ---</span>}
      </InfiniteScroll>
    </div>
  )
}
